﻿using System;
using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;

namespace HIS.Controllers.Master {

    public class Suppliers : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private HISModels.Entities.RefSpecialistGroup reffSpecialistGroup = null;
        //private HISModels.Entities.ReffSpecialist reffSpecialist = null;
        //private HISModels.Entities.ReffSubSpecialist reffSubSpecialist = null;
        #endregion

        public Suppliers() {
            Data.Add("Pagetitle", "Suppliers");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-suppliers")]
        public override void Index() {
            try {
                Data["Pagetitle"] += " :: Suppliers";
                RenderFile("master\\supplierslist.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-suppliers")]
        public void TableList() {
            try {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];

                string code = HttpContext.Current.Request["code"].NullSafeToString();

                string ssearch = "code=" + code;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = "";
                strUri = Global.ServiceUriDictionary["supplierpage"] + Global.ServiceUriDictionary["requestformat"];
                //strUri = ConfigurationManager.AppSettings["supplierpage"] + ConfigurationManager.AppSettings["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));


                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();


                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-suppliers")]
        public void SupplierPrepaireForAdd() {
            try {
                Data["Pagetitle"] += " :: Add Supplier";
                var newSupplier = new HISModels.Entities.Supplier { BankAccount = "", BankAccountName = "", BankBranch = "", CodeValue = "", ContactPerson = "", Fax = "", VAT = 0, InCatalogue = 0, JoinDate = DateTime.Now, RecordStatus = 1, Phone = "", NPWP = "", PPH23 = 0, PPH24 = 0, Mobile = "", TermOp = 0, Id = 0 };


                var viewDataAddress = new ViewDataAddress();

                Address adr = new Address();
                adr.SetNullToEmptyString();
                newSupplier.Addresses.Add(adr);


                var ddlBank = DropDownBank("");
                var ddlSupplier = DropDownSupplierType("");

                Data.Add("viewDataAddress", viewDataAddress);
                Data.Add("supplier", newSupplier);
                Data.Add("ddlBank", ddlBank);
                Data.Add("ddlSupplier", ddlSupplier);
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("master\\supplieredit.html");
                base.RestService.Dispose();
            }

        }

        [Authorization(RoleAction = "master-suppliers")]
        public void SupplierPrepaireForEdit() {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                /// Throw to list if something goes wrong
                GoToUrl("suppliers/"); return;
            }

            try {
                Data["Pagetitle"] += " :: Edit Supplier";

                //get supplier
                string strUri = Global.ServiceUriDictionary["supplier"] + id + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                string temp = stringReader.ReadToEnd();
                var supplier = JsonConvert.DeserializeObject<Supplier>(temp);
                supplier.SetNullToEmptyString();

                //ViewModelAddress
                ViewDataAddress viewDataAddress;
                var address = supplier.Addresses.FirstOrDefault();
                if (address == null) {
                    viewDataAddress = new ViewDataAddress();
                } else {
                    strUri = Global.ServiceUriDictionary["addressbyid"] + address.Id + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.GetJson(strUri);
                    viewDataAddress = JsonConvert.DeserializeObject<ViewDataAddress>(stringReader.ReadToEnd());
                }





                var ddlBank = DropDownBank(supplier.BankId.ToString());
                var ddlSupplierType = DropDownSupplierType(supplier.SupplierTypeId.ToString());
                
                Data.Add("viewDataAddress", viewDataAddress);
                Data.Add("supplier", supplier);
                Data.Add("ddlBank", ddlBank);
                Data.Add("ddlSupplier", ddlSupplierType);
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {



                RenderFile("master\\supplieredit.html");
                if (stringReader != null) stringReader.Dispose();

                base.RestService.Dispose();
            }

        }

        public string DropDownBank(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            //strUri = ConfigurationManager.AppSettings["banklist"] + ConfigurationManager.AppSettings["requestformat"];
            strUri = Global.ServiceUriDictionary["banklist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.Bank> listSp = JsonConvert.DeserializeObject<List<Bank>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                //activeArr.Add(new object[] { "", Name = "- All Hospitals -" });
                //activeArr.Add(new object[] { 1, Name = "Siloam Karawaci" });
                //activeArr.Add(new object[] { 2, Name = "Siloam Bonjer" });


                foreach (Bank item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("BankId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                // stringReaderDropDown.Dispose();
            }
            return strResult;
        }
        public string DropDownSupplierType(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            //strUri = ConfigurationManager.AppSettings["banklist"] + ConfigurationManager.AppSettings["requestformat"];
            strUri = Global.ServiceUriDictionary["suppliertype"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.Bank> listSp = JsonConvert.DeserializeObject<List<Bank>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                //activeArr.Add(new object[] { "", Name = "- All Hospitals -" });
                //activeArr.Add(new object[] { 1, Name = "Siloam Karawaci" });
                //activeArr.Add(new object[] { 2, Name = "Siloam Bonjer" });


                foreach (Bank item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("SupplierTypeId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                // stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [Authorization(RoleAction = "master-supplier")]
        public void SaveSupplier() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            int id = 0;
            try {
                Supplier supplier = new Supplier();
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                Utils.Helper.SetNullToEmptyString(supplier);

                if (id == 0) {
                    supplier.Addresses.Add(new Address());
                } else {
                    strUri = Global.ServiceUriDictionary["supplier"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    supplier = JsonConvert.DeserializeObject<Supplier>(stringReader.ReadToEnd());
                    if (supplier.Addresses.Count == 0) {
                        supplier.Addresses.Add(new Address());
                    }
                }

                // get supplier data
                supplier.PostHandler<HISModels.Entities.Supplier>();
                supplier.CodeValue = supplier.CodeValue.ToUpper();
                // get address data
                // assumtion there is only one address in one supplier

                var viewDataAddress = new ViewDataAddress();
                viewDataAddress.PostHandler<ViewDataAddress>();
                var address = supplier.Addresses.FirstOrDefault();


                viewDataAddress.SetDataToAddress(address);
                strUri = Global.ServiceUriDictionary["supplier"] + Global.ServiceUriDictionary["requestformat"];

                if (id == 0) // new
                {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(supplier));
                } else //edit
                {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(supplier));
                }



                if (stringReader == null) {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + supplier.Id + "\"}";

                } else {


                    string temp = stringReader.ReadToEnd();
                    supplier = JsonConvert.DeserializeObject<Supplier>(temp);
                    if (supplier == null) {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + id + "\"}";
                    } else {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + supplier.Id + "\"}";
                    }

                }

            } catch (Exception ex) {
                strNotification = Helper.ErrorMessage(ex.Message);
                strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + id + "\"}";
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-supplier")]
        public void DeleteSupplier() {
            StringReader stringReader = null;
            int id = 0;
            int resultId = 0;  // ok = 1; ko = 0
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("supplier/");
                return;
            }

            try {
                //doctor = new HISModels.Entities.Doctor();
                //string strUri = Data["servicerooturl"] + "sys/actiongroups/?format=json";
                string strUri = Global.ServiceUriDictionary["supplier"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));

                if (stringReader == null) {
                    //error was here
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    resultId = 0;
                } else {
                    string temp = stringReader.ReadToEnd();
                    var result = JsonConvert.DeserializeObject<Supplier>(temp);
                    if (result == null) {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        resultId = 0;
                    } else {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        resultId = 1;
                    }

                }





            } catch (Exception ex) {
                strNotification = Helper.ErrorMessage(ex.Message);
                resultId = 0;
            } finally {
                var respondData = JsonConvert.SerializeObject(new { strNotification = strNotification, resultId = resultId });

                HttpContext.Current.Response.Write(respondData);
                base.RestService.Dispose();
            }
        }
    }
}